{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "自建迭代器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class MyIterator:\n",
    "    def __init__(self):\n",
    "        self.n = 1\n",
    "\n",
    "    def __iter__(self):\n",
    "        return self  # 迭代器返回自己\n",
    "\n",
    "    def __next__(self):\n",
    "        if self.n <= 3:\n",
    "            result = self.n\n",
    "            self.n += 1\n",
    "            return result\n",
    "        else:\n",
    "            raise StopIteration  # 到头啦！\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "用法\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for num in MyIterator():\n",
    "    print(num)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    " 读取 CSV（读进来变成 DataFrame）：\n",
    "python\n",
    "复制\n",
    "编辑\n",
    "df = pd.read_csv(\"data.csv\")\n",
    "print(df)\n",
    " 写入 CSV（保存为文件）：\n",
    "python\n",
    "复制\n",
    "编辑\n",
    "df.to_csv(\"new_data.csv\", index=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df.head()           # 看前5行\n",
    "df.tail(3)          # 看最后3行\n",
    "df[\"Age\"]           # 取出一列\n",
    "df.describe()       # 简单统计信息\n",
    "df[df[\"Age\"] > 30]  # 条件筛选"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "isnull"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1️⃣ 找出哪一行有缺失\n",
    "python\n",
    "复制\n",
    "编辑\n",
    "df[df[\"Age\"].isnull()]\n",
    "2️⃣ 统计每列缺失的数量\n",
    "python\n",
    "复制\n",
    "编辑\n",
    "df.isnull().sum()\n",
    "输出：\n",
    "\n",
    "go\n",
    "复制\n",
    "编辑\n",
    "Name    0\n",
    "Age     1\n",
    "dtype: int64\n",
    "3️⃣ 删除含缺失值的行\n",
    "python\n",
    "复制\n",
    "编辑\n",
    "df.dropna()\n",
    "4️⃣ 用其他值填充缺失值\n",
    "python\n",
    "复制\n",
    "编辑\n",
    "df[\"Age\"].fillna(0)\n",
    "你可以填 0、平均数、\"未知\"，或者任何合理的值。\n",
    "\n",
    "🔄 四、和 notnull() 是一对！\n",
    "python\n",
    "复制\n",
    "编辑\n",
    "df[\"Age\"].notnull()\n",
    "notnull() 和 isnull() 正好相反，是判断非缺失的。\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "pylearn",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.9.21"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
